<?php
include "utils/HttpRequest.php";
include "utils/ApiResponse.php";

header("Content-Type: application/json");

// 路由表，键是请求方法和路径的组合，值是对应的回调函数
$routes = [
    'GET/users' => function() {
        $users = [
            ["id" => 1, "name" => "John Doe", "email" => "john@example.com"],
            ["id" => 2, "name" => "Jane Doe", "email" => "jane@example.com"]
        ];
        echo json_encode($users);
    },
    'POST/users' => function() {
        // 假设这里会有一些逻辑来处理新用户的创建
        echo json_encode(["message" => "User created"]);
    },
    'GET/users/{id}' => function($params) {
        // 模拟查找特定ID的用户
        $user = ["id" => $params['id'], "name" => "John Doe", "email" => "john@example.com"];
        echo json_encode($user);
    },
    'GET/video' => function() {
        $curl = new HttpRequest();
        $response = $curl->get('https://m1-a1.cloud.nnpp.vip:2223/api/v/');
        ApiResponse::success($response);
    },
];

// 获取当前请求的方法和路径
$method = $_SERVER['REQUEST_METHOD'];
$request = parse_url($_SERVER['REQUEST_URI']);
$path = $request['path'];

// 清除路径中的前后斜杠
$path = trim($path, '/');

// 查找路由
$routeKey = $method . '/' . $path;

// 参数提取（例如/users/1 -> ['id' => 1]）
$params = [];
if (preg_match('/\{([a-z]+)\}/i', $routeKey, $matches)) {
    foreach ($matches as $param) {
        $paramValue = str_replace('{' . $param . '}', '', $path);
        $params[$param] = $paramValue;
        $routeKey = str_replace('{' . $param . '}', $param, $routeKey);
    }
}

// 如果找到了匹配的路由，则调用对应的回调函数
if (isset($routes[$routeKey])) {
    $routes[$routeKey]($params);
} else {
    http_response_code(404); // Not Found
    echo json_encode(["error" => "Route not found"]);
}
?>